function getParentDir(dir) {
    return new java.io.File(dir).parent;
}

function FileChooser(options) {
    // 当前文件列表数据
    this.data = [];
    // 当前被选中的位置
    this.selectedPos = -1;
    this.options = options;
    this.view = this.renderView();
}

FileChooser.prototype.renderView = function () {
    let view = ui.inflate(this.xml);
    view.fileList.on("item_bind", (itemView, itemHolder) => {
        // 绑定勾选框的勾选事件
        itemView.checkbox.on("check", (checked) => {
            let position = itemHolder.position;
            if (checked) {
                this.selectFile(position);
            } else {
                this.unselectFile(position);
            }
        });
    });
    view.fileList.on("item_click", (item, i, itemView) => {
        // 返回上一级
        if (item.fileName == '返回上一级') {
            this.up();
            return;
        }
        // 如果是文件夹被点击，则进入该文件夹
        if (item.isDir) {
            this.setCurrentDir(item.filePath);
        } else {
            // 否则是文件被点击，则切换勾选框状态
            itemView.checkbox.toggle();
        }
    });
    return view;
}

FileChooser.prototype.xml = (
    <vertical>
        <list id="fileList">
            <horizontal w="*">
                <checkbox id="checkbox" visibility="{{this.checkable ? 'visible' : 'gone'}}" checked="{{this.checked}}" />
                <img src="@drawable/{{this.icon}}" w="40dp" h="40dp" scaleType="fitXY" tint="{{this.tint}}" />
                <text text="{{this.fileName}}" h="*" textSize="16sp" textColor="#373737" marginLeft="8dp"
                    gravity="center" maxLines="1" ellipsize="end" />
            </horizontal>
        </list>
    </vertical>
);

// 勾选文件(夹)
FileChooser.prototype.selectFile = function (position) {
    let adapter = this.view.fileList.adapter;
    // 获取之前被选中的位置
    let oldSelectedPos = this.selectedPos;
    // 因为是单选，勾选一个文件时要把之前勾选的文件取消掉
    // 如果大于0，说明之前有被选中的文件(夹)
    if (oldSelectedPos >= 0) {
        // 取消他的选中状态
        this.data[oldSelectedPos].checked = false;
        // 通知这一项更新
        adapter.notifyItemChanged(oldSelectedPos);
    };
    // 设置当前被选中的位置
    this.selectedPos = position;
}

// 取消勾选文件(夹)
FileChooser.prototype.unselectFile = function (position) {
    if (this.selectedPos == position) {
        this.selectedPos = -1;
    }
}

FileChooser.prototype.listFiles = function (dir) {
    let options = this.options;
    //筛选出js文件
    let jsFiles = files.listDir(dir, function (name) {
        return name.endsWith(".js");
    })
    let list = Array.prototype.map.call(jsFiles, (name) => {
        // 文件的绝对路径
        let absPath = files.join(dir, name);
        // 该文件是否是文件夹
        let isDir = files.isDir(absPath);
        //是否可勾选
        let checkable;
        if (isDir) {
            checkable = options.canChooseDir;
        } else {
            checkable = options.canChooseFile;
        }
        return {
            fileName: name,
            filePath: absPath,
            checkable: checkable,
            // 图标
            icon: isDir ? "ic_folder_black_48dp" :
                "ic_insert_drive_file_black_48dp",
            // 图标颜色
            tint: isDir ? "#ffca28" : "#e0e0e0",
            checked: false,
            isDir: isDir
        }
    });
    list.sort(this.comparator());// 排序
    // 如果还有上一级，则在文件列表最前面加上".."用于返回上一级
    // if (getParentDir(this.currentDir) && getParentDir(this.currentDir) != ("/sdcard")) {
    //     list.splice(0, 0, {
    //         fileName: '返回上一级',
    //         checkable: false,
    //         icon: "ic_folder_black_48dp",
    //         tint: '#ffca28',
    //         checked: false,
    //         isDir: true
    //     })
    // }
    return list;
}

FileChooser.prototype.comparator = function () {
    return (lhs, rhs) => {
        if (lhs.isDir !== rhs.isDir) {
            return rhs.isDir - lhs.isDir;
        }
        return lhs.fileName.localeCompare(rhs.fileName);
    }
}

// 设置当前文件夹
FileChooser.prototype.setCurrentDir = function (dir) {
    if (Array.isArray(dir)) {
        this.currentDir = dir[0];
        let that = this;
        this.data = dir.reduce(function (total, value) {
            return total.concat(that.listFiles(value));
        }, []);
        // console.log("array   ", this.data);
    } else {
        this.currentDir = dir;
        this.data = this.listFiles(dir);

        // console.log(this.data);
    }
    this.view.fileList.setDataSource(this.data);
}

FileChooser.prototype.getSelectedFile = function () {
    if (this.selectedPos == -1) {
        return null;
    }
    return this.data[this.selectedPos].filePath;
}

//返回上一级
FileChooser.prototype.up = function () {
    let parent = getParentDir(this.currentDir);
    if (parent == null) {
        return;
    }
    this.setCurrentDir(parent);
}


function FileChooserDialog(options) {
    this.options = Object.assign({}, options);
    this.fillOptions();
}

// 将options参数填充一些选项和默认选项
FileChooserDialog.prototype.fillOptions = function () {
    let options = this.options;
    let canChoose = options.canChoose || [];
    options.canChooseFile = canChoose.indexOf("file") >= 0;
    options.canChooseDir = canChoose.indexOf("dir") >= 0;
    options.wrapInScrollView = false;
    options.canceledOnTouchOutside = options.canceledOnTouchOutside || false;
    options.title = options.title || "选择文件(夹)";
    options.positive = options.positive || "移动到脚本";
    options.negative = options.negative || "退出";
}

FileChooserDialog.prototype.build = function () {
    let options = this.options;
    this.fileChooser = new FileChooser(options);
    this.fileChooser.setCurrentDir(options.dir);
    options.customView = this.fileChooser.view;
    let fileCallback = options.fileCallback;
    return dialogs.build(options)
        .on("positive", () => {
            let selectedFile = this.fileChooser.getSelectedFile();
            fileCallback && fileCallback(selectedFile);
            exit();
        })
        .on("negative", () => {
            exit();
        });
}

FileChooserDialog.build = function (options) {
    return new FileChooserDialog(options).build();
}
FileChooserDialog.build({
    title: '请选择目标文件',
    // 初始文件夹路径
    dir: ["/sdcard/Android/data/com.tencent.mm/MicroMsg/Download",
        "/storage/emulated/999/Android/data/com.tencent.mm/MicroMsg/Download",
    ],
    // dir: "/我的手机/Android/data/com.tencent.mm/MicroMsg/Download",
    // dir: "/storage/emulated/999/Android/data/com.tencent.mm/MicroMsg/Download",
    // dir: "/Phone/App Twin data/Android/data/com.tencent.mm/MicroMsg/Download",
    // dir: "/sdcard",
    // 可选择的类型，file为文件，dir为文件夹
    canChoose: ["file"],
    // 选择文件后的回调
    fileCallback: (file) => {
        console.log(" move  file", file);
        if (files.getExtension(file) == "js") {
            let a = files.move(file, files.join("/sdcard/脚本/", files.getName(file)))
            toastLog(a ? "文件移动成功" : "文件移动失败,请重试!");
        } else {
            toastLog("非js脚本文件,不可移动!")
        }
    }
})
    .show();